package com.shuorikeji.huohuo.ui.mh;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.adapter.MhViewPagerAdapter;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.MhZjDetailInfoMainBean;
import com.shuorikeji.huohuo.bean.MhZjDetailInfoSubBean;
import com.shuorikeji.huohuo.bean.MhZjInfoBean;
import com.shuorikeji.huohuo.bean.MhZjInfoMainBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.DialogUtil;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.shuorikeji.huohuo.view.JapaneseComicPageTransformer;
import com.shuorikeji.huohuo.view.VerticalPageTransformer;
import com.shuorikeji.huohuo.view.ViewPager2JzTransformer;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import androidx.viewpager2.widget.ViewPager2;
import butterknife.BindView;

public class SeeMhActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.vp_mh)
    ViewPager2 vpMh;
    @BindView(R.id.rl_main)
    RelativeLayout rlMain;
    @BindView(R.id.ll_top_1)
    LinearLayout llTop1;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_sc)
    ImageView ivSc;
    @BindView(R.id.iv_download)
    ImageView ivDownload;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.iv_pl)
    ImageView ivPl;
    @BindView(R.id.iv_ml)
    ImageView ivMl;
    @BindView(R.id.iv_jd)
    ImageView ivJd;
    @BindView(R.id.iv_night_mode)
    ImageView ivNightMode;
    @BindView(R.id.iv_set)
    ImageView ivSet;
    @BindView(R.id.rl_pl)
    RelativeLayout rlPl;
    @BindView(R.id.tv_pls)
    TextView tvPls;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.ll_ml)
    LinearLayout llMl;
    @BindView(R.id.ll_jd)
    LinearLayout llJd;
    @BindView(R.id.ll_night_mode)
    LinearLayout llNightMode;
    @BindView(R.id.ll_set)
    LinearLayout llSet;
    @BindView(R.id.tv_zj_info)
    TextView tvZjInfo;
    @BindView(R.id.tv_syz)
    TextView tvSyz;//上一话
    @BindView(R.id.tv_xyz)
    TextView tvXyz;//下一话
    @BindView(R.id.sb_zj_jd)
    SeekBar sbZjJd;
    @BindView(R.id.ll_sec_jd)
    LinearLayout llSecJd;
    @BindView(R.id.tv_ml)
    TextView tvMl;
    @BindView(R.id.tv_jd)
    TextView tvJd;
    @BindView(R.id.tv_night_mode)
    TextView tvNightMode;
    @BindView(R.id.tv_set)
    TextView tvSet;

    private int MH_ID;
    private int ZJ_ID;
    private int IS_ADD_SJ;//0未添加 1已添加
    private int PLS;
    private MhViewPagerAdapter mhViewPagerAdapter;
    private List<String> mhList = new ArrayList<>();
    private Dialog shareDialog;
    private Dialog mlDialog;
    private int curMhZjListPage;
    private int mhAllZjCount;
    private List<MhZjInfoBean> mhZjList = new ArrayList<>();
    private MhZjDetailInfoSubBean mhZjQhInfo;
    private int nightMode = 1;//夜间模式 1未开启；2开启
    private Dialog setDialog;
    private int curMhZjIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_see_mh);
    }

    @Override
    protected void initData() {
        setTopBottomViewState(1);
        initAdapter();
        initIntent();
        initClick();
    }

    /**
     * top bottom view显示状态
     *
     * @param flag 1隐藏
     *             2显示
     */
    private void setTopBottomViewState(int flag) {
        llTop1.setVisibility((flag == 1) ? View.GONE : View.VISIBLE);
        llBottom.setVisibility((flag == 1) ? View.GONE : View.VISIBLE);
    }

    private void initAdapter() {
        mhViewPagerAdapter = new MhViewPagerAdapter(SeeMhActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        if (llTop1.getVisibility() == View.VISIBLE) {
                            setTopBottomViewState(1);
                        } else {
                            setTopBottomViewState(2);
                        }
                        break;
                }
            }
        });
        vpMh.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        vpMh.setPageTransformer(new VerticalPageTransformer());
        vpMh.setAdapter(mhViewPagerAdapter);
        vpMh.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                // 页面变化时执行的操作
                //Log.i("wxl", "当前章节的第几页：" + position);
                curMhZjIndex = position;
                addMhReadHis();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // 滑动状态改变
                switch (state) {
                    case ViewPager2.SCROLL_STATE_DRAGGING:
                        //正在拖动
                        //此处处理下一章节
                        if (curMhZjIndex == 0) {
                            if (mhZjQhInfo != null) {
                                if (mhList.size() == 0) {
                                    if (BusinessUtils.isEmpty(mhZjQhInfo.getNext_chapter().getTitle())) {
                                        ToastShowUtil.showToastCenter(SeeMhActivity.this, "当前是最后一话");
                                    } else {
                                        ZJ_ID = mhZjQhInfo.getNext_chapter().getId();
                                        getMhZjList(false);
                                    }
                                } else {
                                    if (BusinessUtils.isEmpty(mhZjQhInfo.getUp_chapter().getTitle())) {
                                        ToastShowUtil.showToastCenter(SeeMhActivity.this, "当前是第一话");
                                    } else {
                                        ZJ_ID = mhZjQhInfo.getUp_chapter().getId();
                                        getMhZjList(false);
                                    }
                                }
                            }
                        } else if (curMhZjIndex == mhList.size() - 1) {
                            if (mhZjQhInfo != null) {
                                if (BusinessUtils.isEmpty(mhZjQhInfo.getNext_chapter().getTitle())) {
                                    ToastShowUtil.showToastCenter(SeeMhActivity.this, "当前是最后一话");
                                } else {
                                    ZJ_ID = mhZjQhInfo.getNext_chapter().getId();
                                    getMhZjList(false);
                                }
                            }
                        }
                        break;
                    case ViewPager2.SCROLL_STATE_SETTLING:
                        //自动滚动
                        break;
                    case ViewPager2.SCROLL_STATE_IDLE:
                        //空闲状态
                        break;
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                // 页面正在滑动
            }
        });
    }

    private void initIntent() {
        Intent intent = getIntent();
        MH_ID = intent.getIntExtra("MH_ID", -1);
        ZJ_ID = intent.getIntExtra("ZJ_ID", -1);
        IS_ADD_SJ = intent.getIntExtra("IS_ADD_SJ", 0);
        PLS = intent.getIntExtra("PLS", 0);
        curMhZjListPage = 1;
        ivSc.setImageResource((IS_ADD_SJ == 0) ? R.mipmap.icon_see_mh_sc : R.mipmap.icon_mh_ysc);
        tvPls.setText(String.valueOf(PLS));
        getMhZjList(false);
    }

    private void getMhZjDetail() {
        mPresenter.getMhZjDetail(true, MH_ID, ZJ_ID, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        MhZjDetailInfoMainBean data = (MhZjDetailInfoMainBean) object;
                        mhZjQhInfo = data.getData();
                        setZjJd();
                        tvZjInfo.setText(data.getData().getChapter().getTitle());
                        mhList.clear();
                        mhList.addAll(data.getData().getChapter().getImages());
                        mhViewPagerAdapter.setData(mhList);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SeeMhActivity.this, msg);
                        break;
                }
            }
        });
    }

    /**
     * 设置章节进度
     */
    private void setZjJd() {
        try {
            BigDecimal bigDecimal = BusinessUtils.divBigDecimal(new BigDecimal(mhZjQhInfo.getChapter().getChapter_number())
                    , new BigDecimal(mhAllZjCount), 2, false);
            sbZjJd.setProgress(BusinessUtils.mul(bigDecimal, new BigDecimal(100), 0).intValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取漫画章节列表
     */
    private void getMhZjList(boolean showMlDialog) {
        mPresenter.getMhZjList(true, MH_ID, 20, curMhZjListPage, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        MhZjInfoMainBean data = (MhZjInfoMainBean) object;
                        mhAllZjCount = data.getData().getChapterList().getTotal();
                        if (curMhZjListPage == 1) {
                            mhZjList.clear();
                        }
                        mhZjList.addAll(data.getData().getChapterList().getData());
                        if (showMlDialog) {
                            DialogUtil.gxMhZjInfo(mhZjList);
                        } else {
                            getMhZjDetail();
                        }
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SeeMhActivity.this, msg);
                        getMhZjDetail();
                        break;
                }
            }
        });
    }

    private void addMhReadHis() {
        mPresenter.addMhReadHis(false, MH_ID, ZJ_ID, curMhZjIndex, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SeeMhActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void showMhMlDialog() {
        mlDialog = DialogUtil.showMhMlDialog(SeeMhActivity.this, mhZjList, mhAllZjCount, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        //上一页
                        if (curMhZjListPage == 1) {
                            ToastShowUtil.showToastCenter(SeeMhActivity.this, "当前已经是第一页了");
                        } else {
                            curMhZjListPage = curMhZjListPage - 1;
                            getMhZjList(true);
                        }
                        break;
                    case 2:
                        //下一页
                        if (mhZjList.size() == mhAllZjCount) {
                            ToastShowUtil.showToastCenter(SeeMhActivity.this, "当前已经是最后一页了");
                        } else {
                            curMhZjListPage = curMhZjListPage + 1;
                            getMhZjList(true);
                        }
                        break;
                    case 3:
                        //开始看漫画
                        MhZjInfoBean data = (MhZjInfoBean) object;
                        ZJ_ID = data.getId();
                        getMhZjDetail();
                        break;
                }
            }
        });
    }

    private void showShareDialog() {
        shareDialog = DialogUtil.showShareDialog(SeeMhActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {

            }
        });
    }

    /**
     * 根据配置设置夜间模式
     */
    private void setNightModeBg() {
        if (nightMode == 1) {
            nightMode = 2;
            llTop1.setBackgroundColor(getResources().getColor(R.color.color_252628));
            llBottom.setBackgroundColor(getResources().getColor(R.color.color_252628));
            vpMh.setBackgroundColor(getResources().getColor(R.color.color_F6F6F6));
            if (IS_ADD_SJ == 0) {
                ivSc.setImageResource(R.mipmap.icon_see_mh_sc_night);
            } else {
                ivSc.setImageResource(R.mipmap.icon_mh_ysc);
            }
            ivDownload.setImageResource(R.mipmap.icon_see_mh_download_night);
            ivShare.setImageResource(R.mipmap.icon_see_mh_share_night);
            ivPl.setImageResource(R.mipmap.icon_see_mh_pl_night);
            tvPls.setTextColor(getResources().getColor(R.color.white_color));
            ivMl.setImageResource(R.mipmap.icon_see_mh_ml_night);
            ivJd.setImageResource(R.mipmap.icon_see_mh_jd_night);
            ivNightMode.setImageResource(R.mipmap.icon_see_mh_night_mode_night);
            ivSet.setImageResource(R.mipmap.icon_see_mh_set_night);
            tvSyz.setTextColor(getResources().getColor(R.color.white_color));
            tvXyz.setTextColor(getResources().getColor(R.color.white_color));
            tvMl.setTextColor(getResources().getColor(R.color.color_BABABA));
            tvJd.setTextColor(getResources().getColor(R.color.color_BABABA));
            tvNightMode.setTextColor(getResources().getColor(R.color.color_BABABA));
            tvSet.setTextColor(getResources().getColor(R.color.color_BABABA));
            tvZjInfo.setTextColor(getResources().getColor(R.color.color_BABABA));
            ivBack.setImageResource(R.mipmap.icon_back_white_1);
        } else {
            nightMode = 1;
            llTop1.setBackgroundColor(getResources().getColor(R.color.white_color));
            llBottom.setBackgroundColor(getResources().getColor(R.color.color_f6f7f8));
            vpMh.setBackgroundColor(getResources().getColor(R.color.white_color));
            if (IS_ADD_SJ == 0) {
                ivSc.setImageResource(R.mipmap.icon_see_mh_sc);
            } else {
                ivSc.setImageResource(R.mipmap.icon_mh_ysc);
            }
            ivDownload.setImageResource(R.mipmap.icon_see_mh_download);
            ivShare.setImageResource(R.mipmap.icon_see_mh_share);
            ivPl.setImageResource(R.mipmap.icon_see_mh_pl);
            tvPls.setTextColor(getResources().getColor(R.color.color_333333));
            ivMl.setImageResource(R.mipmap.icon_see_mh_ml);
            ivJd.setImageResource(R.mipmap.icon_see_mh_jd);
            ivNightMode.setImageResource(R.mipmap.icon_see_mh_night_mode);
            ivSet.setImageResource(R.mipmap.icon_see_mh_set);
            tvSyz.setTextColor(getResources().getColor(R.color.color_333333));
            tvXyz.setTextColor(getResources().getColor(R.color.color_333333));
            tvMl.setTextColor(getResources().getColor(R.color.color_333333));
            tvJd.setTextColor(getResources().getColor(R.color.color_333333));
            tvNightMode.setTextColor(getResources().getColor(R.color.color_333333));
            tvSet.setTextColor(getResources().getColor(R.color.color_333333));
            tvZjInfo.setTextColor(getResources().getColor(R.color.color_333333));
            ivBack.setImageResource(R.mipmap.icon_back_title);
        }
    }

    private void showSetDialog() {
        setDialog = DialogUtil.showMhSetDialog(SeeMhActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        //调节屏幕亮度
                        float ldValue = (float) object;
                        setScreenLight(ldValue);
                        break;
                    case 2:
                        //设置为系统当前亮度
                        setScreenLight(BusinessUtils.getCurrentScreenLight(SeeMhActivity.this));
                        break;
                    case 3:
                        //卷轴模式
                        vpMh.setPageTransformer(new ViewPager2JzTransformer());
                        break;
                    case 4:
                        //普通模式
                        vpMh.setPageTransformer(new VerticalPageTransformer());
                        break;
                    case 5:
                        //日漫模式
                        vpMh.setPageTransformer(new JapaneseComicPageTransformer());
                        break;
                }
            }
        });
    }

    /**
     * 设置当前 Activity 的屏幕亮度（无需权限）
     *
     * @param brightness 亮度值，范围为 0.0f（最暗）到 1.0f（最亮）
     */
    private void setScreenLight(float brightness) {
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.screenBrightness = brightness;
        window.setAttributes(layoutParams);
    }

    private void addSj() {
        mPresenter.addMhSj(true, MH_ID, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        IS_ADD_SJ = 1;
                        ivSc.setImageResource(R.mipmap.icon_mh_ysc);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SeeMhActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void deleteSj() {
        mPresenter.deleteMhSj(true, MH_ID, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        IS_ADD_SJ = 0;
                        ivSc.setImageResource(R.mipmap.icon_see_mh_sc);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(SeeMhActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void initClick() {
        sbZjJd.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true; // 拦截所有触摸事件
            }
        });
        ivBack.setOnClickListener(view -> {
            finish();
        });
        ivShare.setOnClickListener(view -> {
            showShareDialog();
        });
        ivDownload.setOnClickListener(view -> {
            Intent intent = new Intent(SeeMhActivity.this, CacheMhZjActivity.class);
            intent.putExtra("MH_ID", MH_ID);
            startActivity(intent);
        });
        rlPl.setOnClickListener(view -> {
            Intent intent = new Intent(SeeMhActivity.this, MhPlActivity.class);
            intent.putExtra("MH_ID", MH_ID);
            startActivity(intent);
        });
        llMl.setOnClickListener(view -> {
            if (mhZjList != null && mhZjList.size() > 0) {
                showMhMlDialog();
            } else {
                ToastShowUtil.showToastCenter(SeeMhActivity.this, "漫画章节获取失败，请稍后重试");
            }
        });
        tvSyz.setOnClickListener(view -> {
            if (mhZjQhInfo != null) {
                if (BusinessUtils.isEmpty(mhZjQhInfo.getUp_chapter().getTitle())) {
                    ToastShowUtil.showToastCenter(SeeMhActivity.this, "当前是第一话");
                } else {
                    ZJ_ID = mhZjQhInfo.getUp_chapter().getId();
                    getMhZjDetail();
                }
            } else {
                ToastShowUtil.showToastCenter(SeeMhActivity.this, "暂无漫画相关信息");
            }
        });
        tvXyz.setOnClickListener(view -> {
            if (mhZjQhInfo != null) {
                if (BusinessUtils.isEmpty(mhZjQhInfo.getNext_chapter().getTitle())) {
                    ToastShowUtil.showToastCenter(SeeMhActivity.this, "当前是最后一话");
                } else {
                    ZJ_ID = mhZjQhInfo.getNext_chapter().getId();
                    getMhZjDetail();
                }
            } else {
                ToastShowUtil.showToastCenter(SeeMhActivity.this, "暂无漫画相关信息");
            }
        });
        llJd.setOnClickListener(view -> {
            if (llSecJd.getVisibility() == View.VISIBLE) {
                llSecJd.setVisibility(View.GONE);
            } else {
                llSecJd.setVisibility(View.VISIBLE);
            }
        });
        llNightMode.setOnClickListener(view -> {
            setNightModeBg();
        });
        llSet.setOnClickListener(view -> {
            showSetDialog();
        });
        ivSc.setOnClickListener(view -> {
            if (IS_ADD_SJ == 0) {
                //添加书架
                addSj();
            } else {
                //删除书架
                deleteSj();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusinessUtils.clearDialog(shareDialog);
        BusinessUtils.clearDialog(mlDialog);
        BusinessUtils.clearDialog(setDialog);
    }
}